import base64 from 'base64-js'
import {readFile, readFileSync} from 'fs'
import picgo from 'picgo'

export default class Uploader {
  handle(ctx: picgo) {
    for (let i in ctx.input) {
      let img = this.upload(ctx, ctx.input[i])
      img.then((imgUrl) => {
        ctx.log.info(imgUrl)
        ctx.output[i] = imgUrl;
      })

    }
  }

  upload =
      async (ctx: picgo, filePath: string) => {
    let f = readFileSync(filePath)

    let imgStr = base64.fromByteArray(f)
    const config = ctx.getConfig('picBed.gitee')

    let repo = config.repo
    let username = config.username
    let token = config.token
    let path = config.path
    let branch = config.branch

    let time = Date.now() + '_' + (Math.floor(Math.random() * 10000))

    let extName = this.getExtName(filePath)

    if (extName != '') {
      extName = `.${extName}`
    }

    let name = `${time}${extName}`

    let uri = `https://gitee.com/api/v5/repos/${username}/${repo}/contents/${
        path}/${name}`

    let formData = {
      'access_token': token,
      'message': 'upload by picgo-plugin-gitee',
      'branch': branch,
    };
    // console.log(formData)

    formData['content'] = imgStr

    try {
      let response = await ctx.Request.request({
        method: 'post',
        uri: uri,
        formData: formData,
      })

      return JSON.parse(response).content.download_url
    } catch (error) {
      // ctx.log.error(error)
      return 'have error'
    }
  }

  getExtName = (filePath: string) => {
    let last = filePath.lastIndexOf('.')
    if (last != -1) {
      return filePath.substring(last + 1, filePath.length)
    }
    return ''
  }
}
